
import 'dart:collection';
import 'dart:convert';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/login_data_manager.dart';
import 'package:flutter_reader/dao/me_data_manager.dart';
import 'package:flutter_reader/pages/Login/login_nav_page.dart';
import 'package:flutter_reader/pages/Login/login_page.dart';
import 'package:flutter_reader/pages/home/check/check_page.dart';
import 'package:flutter_reader/pages/home/recharge/recharge_page.dart';
import 'package:flutter_reader/pages/me/bind_phone_page.dart';
import 'package:flutter_reader/pages/me/connect_us_page.dart';
import 'package:flutter_reader/pages/me/consumption_page.dart';
import 'package:flutter_reader/pages/me/download_progress_dialog.dart';
import 'package:flutter_reader/pages/me/exchange_page.dart';
import 'package:flutter_reader/pages/me/feedback_page.dart';
import 'package:flutter_reader/pages/me/recharge_recording_page.dart';
import 'package:flutter_reader/pages/me/vip_page.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/tools/global_state.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_reader/tools/globals.dart' as globals;
import 'package:url_launcher/url_launcher.dart';

class MePage extends StatefulWidget {
  MePage({Key key}) : super(key: key);

  @override
  _MePageState createState() {
    return _MePageState();
  }
}

class _MePageState extends State<MePage> {

  bool haveCheck = false;

  bool _hasLogin = false;

  bool _isLoading = true;

  String nickName;
  int coin = 0;
  int gift = 0;
  String vipDate = '';
  String userID = '';
  var mobile;


  @override
  void initState() {
    print(DateTime.now().toString());
    firstInit();
    // initPlatformState();
    super.initState();
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  // }

  firstInit() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    final fullSessionID = preferences.get('fullSessionID');
    print(preferences.getString('login').toString());
    if(preferences.getString('login') == 'true'){
      LoginDao.fetchUserData(fullSessionID).then((value){
        print(value['success']);
        ///已登录的用户
          if(value['success'] == true){
            print('coin:${coin}');
            if (this.mounted) {
              setState(() {
                coin = value['data']['coin'];
                gift = value['data']['gift'];
                nickName = value['data']['nickname'];
                vipDate = value['data']['vip_date'];
                vipDate = '';
                mobile = value['data']['mobile'];
                userID = value['data']['uid'];
                _hasLogin = true;
              });
            }
          }
          else{
            print('数据获取失败1');
            print(value);
          }
        });
    }
    else{
      print('2');
      LoginDao.fetchUserData(globals.fullSessionID).then((value){
        print(value['success']);
        ///游客
          if(value['success'] == true){
            print('coin:${value['data']['coin']}');
            if (this.mounted) {
              setState(() {
                coin = value['data']['coin'];
                gift = value['data']['gift'];
                vipDate = value['data']['vip_date'];
              });
            }
          }
          else{
            print('数据获取失败2');
            print(value);
          }
        });
    }
  }


  checkLoginState() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    final hasLogin = preferences.getString('login');
    print(hasLogin);
    print('当前本地session:${preferences.get('fullSessionID')}');
    if (this.mounted) {
      setState(() {
        if(hasLogin == 'true'){
          _hasLogin = true;
        }
        else{
          _hasLogin = false;
        }
      });
    }
  }

  Loginout() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString('login', 'false');
    preferences.setString('fullSessionID', null);
    print(preferences.getString('login'));
    if (this.mounted) {
      setState(() {
        _hasLogin = false;
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return Scaffold(
        backgroundColor: Color.fromRGBO(240, 240, 240, 1),
        body: MediaQuery.removePadding(context: context,
            removeTop: true,
            child: Container(
          child: ListView(
            children: <Widget>[
              _topLabBar(_hasLogin),
              _topList(),
              _middleList(),
              _bottomList()
            ],
          ),
        )));
  }

  Widget _topLabBar(bool hasLogin){
    return Container(
      color: Colors.white,
      height: ScreenUtil().setHeight(1050),
      child: Container(
        child: Column(
          children: <Widget>[
            _iconAndCheck(hasLogin),
            _coinAndTicket(hasLogin),
            _advertise(),
          ],
        ),
      ),
    );
  }

  Widget _iconAndCheck(bool hasLogin){
    return Container(
      height: ScreenUtil().setHeight(400),
      child:Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          hasLogin ?  Container(
            margin: EdgeInsets.only(
                left: ScreenUtil().setWidth(80),top: ScreenUtil().setHeight(180)),
            child: ClipOval(
              child:Image(
                width: ScreenUtil().setWidth(200),
                image: AssetImage('images/fl_defaultUser.png'),
              ),
            ),
          ) :
          InkWell(
            onTap: (){
              Navigator.push(context, MaterialPageRoute(
                builder: (context) => LoginNavPage()
              )).then((value){
                firstInit();
              });
            },
            child: Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(80),top: ScreenUtil().setHeight(180)),
              child: ClipOval(
                child:Image(
                  width: ScreenUtil().setWidth(200),
                  image: AssetImage('images/fl_user.png'),
                ),
              ),
            ),
          ),
          hasLogin ? Container(
            width: ScreenUtil().setWidth(300),
            height: ScreenUtil().setHeight(200),
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(40),top: ScreenUtil().setHeight(180)),
            padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin:EdgeInsets.only(),
                  child: Text(nickName,style: TextStyle(fontWeight: FontWeight.w500,
                      fontSize: ScreenUtil().setSp(60)),
                  overflow: TextOverflow.ellipsis,),
                ),
                Container(
                  width: ScreenUtil().setWidth(280),
                  height: ScreenUtil().setHeight(60),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                  child: FittedBox(
                    fit: BoxFit.contain,
                    child: Text(
                      "ID: ${userID.toString()}",
                      style: TextStyle(
                        color: Colors.grey
                      ),
                    ),
                  )
                )
              ],
            )
          ) : InkWell(
            onTap: (){
              Navigator.push(context, MaterialPageRoute(
                  builder: (context) => LoginNavPage()
              )).then((value){
                firstInit();
              });
            },
            child: Container(
              height: ScreenUtil().setHeight(200),
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(40),top: ScreenUtil().setHeight(180)),
              padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
              child: Container(
                height: ScreenUtil().setHeight(200),
                padding: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                child: Text('登录/注册',
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(55)
                  ),),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _coinAndTicket(bool hasLogin){
    return Container(
      height: ScreenUtil().setHeight(150),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(70)),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              decoration: BoxDecoration(
                  border:Border(
                      right: BorderSide(
                          width: 1,
                          color: Colors.black12
                      )
                  )
              ),
              child: Column(
                children: <Widget>[
                  Container(
                    child: Text(coin.toString(),
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(60),
                          fontWeight: FontWeight.w500
                      ),),
                  ),
                  Container(
                    child: Text(
                      '书币',
                      style: TextStyle(
                          color: Colors.black26,
                          fontSize: ScreenUtil().setSp(35)
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Text(gift.toString(),
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(60),
                          fontWeight: FontWeight.w500
                      ),),
                  ),
                  Container(
                    child: Text(
                      '书券',
                      style: TextStyle(
                          color: Colors.black26,
                          fontSize: ScreenUtil().setSp(35)
                      ),
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _advertise(){
    return vipDate == '' ?
    InkWell(
      onTap: _jumpToVipPage,
      child: Container(
        width: ScreenUtil().setWidth(1045),
        height: ScreenUtil().setHeight(300),
        margin: EdgeInsets.only(top: ScreenUtil().setHeight(70),
            left: ScreenUtil().setWidth(40),
            right: ScreenUtil().setWidth(40)),
        decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Colors.black38,
                blurRadius: 10.0,
                offset: Offset(3.0, 3.0),),
            ],
            gradient: LinearGradient(
              colors: <Color>[
                Color(0xffb31217),
                Color(0xffe52d27)
              ],
            ),
            borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child:Row(
          children: <Widget>[
            Container(
              width: ScreenUtil().setWidth(270),
              height: ScreenUtil().setHeight(150),
              decoration: BoxDecoration(
                  border: Border(
                      right: BorderSide(
                          width: 1,
                          color: Colors.white60
                      )
                  )
              ),
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(15),
                  top: ScreenUtil().setHeight(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    child: Text('开通爱看VIP',
                        style: TextStyle(color: Colors.white,
                            fontWeight: FontWeight.w900,
                            fontSize: ScreenUtil().setSp(40))),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      bottom: ScreenUtil().setHeight(0),),
                    child: Text('暂未开通',style: TextStyle(
                        color: Colors.white60,fontSize: ScreenUtil().setSp(30)
                    ),
                      textAlign: TextAlign.left,),
                  )
                ],
              ),
            ),
            Container(
              width: ScreenUtil().setWidth(450),
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(50)),
              child:FittedBox(
                fit: BoxFit.contain,
                child: Text('开通vip畅销全站资源',
                  style: TextStyle(color: Color.fromRGBO(245, 226, 221, 1),
                      fontWeight: FontWeight.w500,
                      letterSpacing: 2),
                ),
              )
            ),
            Container(
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(50)),
              child: Image(
                width: ScreenUtil().setWidth(180),
                image: AssetImage('images/backImage2.png'),
              ),
            )
          ],
        ),
      ),
    )
        :
    Container(
      width: ScreenUtil().setWidth(1045),
      height: ScreenUtil().setHeight(300),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(70),
          left: ScreenUtil().setWidth(40),
          right: ScreenUtil().setWidth(40)),
      decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black38,
              blurRadius: 10.0,
              offset: Offset(3.0, 3.0),),
          ],
          gradient: LinearGradient(
            colors: <Color>[
              Color(0xffDBE6F6),
              Color(0xffC5796D)
            ],
          ),
          borderRadius: BorderRadius.all(Radius.circular(10))
      ),
      child:Center(
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(80)),
              child: Text(
                '-- 您已开通爱看VIP 畅读全站图书 --',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: ScreenUtil().setSp(45),
                  fontWeight: FontWeight.w600
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(30)),
              child: Text(
                '过期时间：${vipDate}',
                style: TextStyle(
                    color: Colors.white,
                  fontWeight: FontWeight.w300,
                  fontSize: ScreenUtil().setSp(40)
                ),
              ),
            )
          ],
        )
      ),
    );
  }

  Widget _func(){
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Image(
                      color: Color(0xffe53935),
                      width: ScreenUtil().setWidth(110),
                      image: AssetImage('images/fl_check.png'),
                    ),
                  ),
                  Container(
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                      child: Text('签到有礼'),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Image(
                      color: Color(0xffe53935),
                      width: ScreenUtil().setWidth(110),
                      image: AssetImage('images/fl_recorder.png'),
                    ),
                  ),
                  Container(
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                      child: Text('充值记录'),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Image(
                      color: Color(0xffe53935),
                      width: ScreenUtil().setWidth(110),
                      image: AssetImage('images/flu_customRe.png'),
                    ),
                  ),
                  Container(
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                      child: Text('消费记录'),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              child: Column(
                children: <Widget>[
                  Container(
                    child: Image(
                      color: Color(0xffe53935),
                      width: ScreenUtil().setWidth(110),
                      image: AssetImage('images/fl_change.png'),
                    ),
                  ),
                  Container(
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                      child: Text('兑换专区'),
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  _topList(){
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
      decoration: BoxDecoration(
        color: Colors.white
      ),
      height: ScreenUtil().setHeight(300),
        child: Column(
          children: <Widget>[
            _ListLine(false, 'images/fl_recharge.png', '书币充值', _jumpToRecharge),
            _ListLine(true, 'images/fl_king.png', '开通会员', _jumpToVipPage)
          ],
        )
    );
  }

  _middleList(){
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(30)),
      height: ScreenUtil().setHeight(590),
      child: Column(
        children: <Widget>[
          _ListLine(false, 'images/fl_check.png', '签到有礼', _jumpToCheckPage),
          _ListLine(false, 'images/fl_recorder.png', '充值记录', _jumpToRechargeRecordPage),
          _ListLine(false, 'images/fl_money.png', '消费记录', _jumpToConsumptionPage),
          _ListLine(true, 'images/fl_change.png', '兑换专区', _jumpToExchangePage),
        ],
      ),
    );
  }

  _bottomList(){
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
      height: ScreenUtil().setHeight(590),
      child: Column(
        children: <Widget>[
          _ListLineWithSubtitle(false, 'images/fl_phone.png', '绑定手机', "",_jumpToBind),
          _ListLine(false, "images/fl_connectWe.png", "联系客服", _jumpToConnect),
          _ListLine(false, 'images/fl_review.png', '意见反馈', _jumpToFeedbackPage),
          _ListLine(true, "images/fl_update.png", '版本更新', _update)
        ],
      ),
    );
  }

  Widget _ListLine(bool isBottom, String image, String title,
       GestureTapCallback jumpFunc){
    return InkWell(
      onTap: jumpFunc,
      child: Container(
        height: ScreenUtil().setHeight(140),
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(40),
              bottom: ScreenUtil().setHeight(30)),
              child: Image(
                fit: BoxFit.contain,
                width: ScreenUtil().setWidth(70),
                height: ScreenUtil().setHeight(70),
                image: AssetImage(image),
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(50)),
              width: ScreenUtil().setWidth(950),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          width: 1,
                          color: isBottom == true ? Colors.white : Colors.black12
                      )
                  )
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(30)),
                    height: ScreenUtil().setHeight(70),
                    child: FittedBox(
                      fit: BoxFit.contain,
                      child: Text(
                        title,
                        style: TextStyle(
                            fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                        bottom: ScreenUtil().setHeight(30)),
                    child: Image(
                      width: ScreenUtil().setWidth(80),
                      height: ScreenUtil().setHeight(50),
                      image: AssetImage('images/fl_arrow.png'),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _ListLineWithSubtitle(bool isBottom, String image, String title,String subTitle,
      GestureTapCallback jumpFunc){
    return InkWell(
      onTap: jumpFunc,
      child: Container(
        height: ScreenUtil().setHeight(140),
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(40),
                  bottom: ScreenUtil().setHeight(30)),
              child: Image(
                fit: BoxFit.contain,
                width: ScreenUtil().setWidth(80),
                height: ScreenUtil().setHeight(80),
                image: AssetImage(image),
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(50)),
              width: ScreenUtil().setWidth(950),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          width: 1,
                          color: isBottom == true ? Colors.white : Colors.black12
                      )
                  )
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(30)),
                    height: ScreenUtil().setHeight(70),
                    child: FittedBox(
                      fit: BoxFit.fitHeight,
                      child: Text(
                        title,
                        style: TextStyle(
                            fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(30)),
                        child: mobile == null ? RichText(
                          text: TextSpan(
                            children: <TextSpan>[
                              TextSpan(text: "绑定即得 ",style: TextStyle(color: Colors.black)),
                              TextSpan(text: "50书币", style: TextStyle(color: Colors.redAccent))
                            ]
                          ),
                        ):Text(mobile == null ? '绑定即得50书币' : '已绑定${mobile.toString()}'),
                      ),
                      Container(
                        margin: EdgeInsets.only(
                            bottom: ScreenUtil().setHeight(30)),
                        child: Image(
                          width: ScreenUtil().setWidth(80),
                          height: ScreenUtil().setHeight(50),
                          image: AssetImage('images/fl_arrow.png'),
                        ),
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _jumpToRecharge(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => RechargePage()
    ));
  }

  _jumpToVipPage(){
    Navigator.push(context, MaterialPageRoute(
        builder: (context) => VipPage()
    ));
  }

  _jumpToRechargeRecordPage(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => RechargeRecordPage()
    ));
  }

  _jumpToFeedbackPage(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => FeedbackPage()
    ));
  }

  _jumpToConsumptionPage(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => ConsumptionPage()
    ));
  }

  _jumpToCheckPage(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => CheckPage()
    ));
  }

  _jumpToExchangePage(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => ExchangePage()
    ));
  }

  _jumpToBind(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => BindPage(hasMobile: mobile == null || mobile == '' ? false : true,)
    )).then((value){
      firstInit();
    });
  }

  _jumpToConnect(){
    Navigator.push(context, MaterialPageRoute(
      builder: (context) => ConnectUsPage()
    ));
  }

  _update() async{
    MeDao.checkVersion().then((value){
      if(value["data"]["content"] != null)
        {
          showUpdate("", value["data"]['content'], value["data"]['url']);
        }
      else
        {
          final mySnackBar = SnackBar(
          content: new Text('已是最新版本'),
          backgroundColor: Colors.blue,
          duration: Duration(milliseconds: 500),

        );
        Scaffold.of(context).showSnackBar(mySnackBar);
        }
    });
  }



  ///显示更新内容
  ///[version] 最新版本号
  ///[data] 更新内容
  Future<void> showUpdate(String version, String data, String url) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('发现新版本'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(version),
                Text(''),
                Text('更新内容：'),
                Text(data),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () async{
                if (await canLaunch(url)) {
                  await launch(url);
                } else {
                  throw 'Could not launch $url';
                }
              }
            ),
          ],
        );
      },
    );
  }

  ///执行更新操作
  ///[version] 最新版本号
  doUpdate(String version,String url) async {

    //关闭更新内容提示框
    Navigator.of(context).pop();

    //获取权限
    var per = await checkPermission();
    if(per != null && !per){
      return null;
    }

    //开始更新
    return showDialog(
      context: context,
      barrierDismissible: false, // user must tap button!
      child: DownloadProgressDialog(version,url),
    );
  }


  ///检查是否有权限
  checkPermission() async {
    //检查是否已有读写内存权限
    PermissionStatus status = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);

    //判断如果还没拥有读写权限就申请获取权限
    if(status != PermissionStatus.granted){
      var map = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
      if(map[PermissionGroup.storage] != PermissionStatus.granted){
        return false;
      }
    }
  }
}